package com.atguigu.gmall.seckill.consumer;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.mq.config.RabbitService;
import com.atguigu.gmall.seckill.mapper.SeckillMapper;
import com.atguigu.gmall.seckill.pojo.SeckillOrder;
import com.atguigu.gmall.seckill.pojo.UserRecode;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * 秒杀下单的监听者
 */
@Component
public class SeckillOrderAddConsumer {


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillMapper seckillGoodsMapper;

    @Autowired
    private RabbitService rabbitService;

    /**
     * 监听排队消息进行秒杀下单
     * @param msg
     */
    @RabbitListener(queues = "seckill_queue")
    public void  addOrder(String msg){
        //将消息的类型转换为排队信息
        UserRecode userRecode = JSONObject.parseObject(msg, UserRecode.class);
        String username = userRecode.getUsername();
        //        //进行校验,用户是否有未支付的秒杀订单
//        Object o = redisTemplate.boundHashOps("SeckillOrder").get(username);
//        if(o != null){
//            //修改排队的状态
//            userRecode.setStatus(3);
//            //更新用户的排队状态
//            redisTemplate.boundValueOps("SeckillStatus_" + username).set(userRecode);
//            return;
//        }
        String time = userRecode.getTime();
        String goodsId = userRecode.getGoodsId();
        //校验商品
        SeckillGoods seckillGoods = (SeckillGoods) redisTemplate.boundHashOps("SeckillGoods_"+time).get(goodsId);
        if (seckillGoods!=null){
            //商品的类型转换
            Object o = redisTemplate.boundListOps("seckillGoodsQueue_" + goodsId).rightPop();
            //判断库存
            if(o !=null){
                //构建订单信息
                SeckillOrder seckillOrder = new SeckillOrder();
                //replace 替换
                seckillOrder.setId(UUID.randomUUID().toString().replace("-", ""));
                seckillOrder.setGoodsId(goodsId);
                seckillOrder.setNum(userRecode.getNum());
                seckillOrder.setMobile(userRecode.getNum() * seckillGoods.getCostPrice().doubleValue() + "");
                seckillOrder.setUserId(username);
                seckillOrder.setCreateTime(userRecode.getCreateTime());
                seckillOrder.setStatus("0");
                //将订单信息存入redis
                redisTemplate.boundHashOps("SeckillOrder_"+username).put(goodsId,seckillGoods);
                //更新库存 存在超卖问题
//                int i  = seckillGoods.getStockCount()- userRecode.getNum();
//                seckillGoods.setStockCount(i);
                  Long stockNum =redisTemplate.boundHashOps("SeckillGoodsStockNum").increment(goodsId,-1);
                  seckillGoods.setStockCount(stockNum.intValue());
                  if (stockNum>0){
                      redisTemplate.boundHashOps("SeckillGoods_" + time).put(goodsId,seckillGoods);
                  }else {
                      //售出处理 将redis中的商品数据清除掉
                      redisTemplate.boundHashOps("SeckillGoods_"+time).delete(goodsId);
                      //将商品的数据同步到数据库中去
                      seckillGoodsMapper.updateById(seckillGoods);
                  }
                //更新一下排队的状态
                userRecode.setStatus(2);
                userRecode.setMoney(Float.valueOf(seckillOrder.getMoney()));
                userRecode.setOrderId(seckillOrder.getId());
                //更新用户的排队状态
                redisTemplate.boundValueOps("SeckillStatus_"+username).set(userRecode);
                //发送一个延迟消息 记录订单的有效倒计时
                rabbitService.sendMessage("seckill_dead_exchange",
                        "seckill.dead.order",
                        JSONObject.toJSONString(seckillOrder),
                        "300");
                //结束
                return;
            }

        }
        //商品售出 修改排队的状态 下单失败
        userRecode.setStatus(3);
        //更新用户的排队状态
        redisTemplate.boundValueOps("SeckillStatus_"+username).set(userRecode);
        //重复排队标识删除
        redisTemplate.delete("SeckillUserQueue_"+username);
        return;
    }

}
